import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import '../models/expense_model.dart';
import '../screens/add_expense_screen.dart';
import '../themes/expense_theme.dart';

/// 快速添加记账的浮动按钮
class QuickAddFAB extends StatefulWidget {
  const QuickAddFAB({super.key});

  @override
  State<QuickAddFAB> createState() => _QuickAddFABState();
}

class _QuickAddFABState extends State<QuickAddFAB>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _rotationAnimation;
  late Animation<double> _scaleAnimation;
  bool _isExpanded = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    _rotationAnimation = Tween<double>(
      begin: 0.0,
      end: 0.75,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));

    _scaleAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.elasticOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  void _toggleExpanded() {
    setState(() {
      _isExpanded = !_isExpanded;
    });

    if (_isExpanded) {
      _animationController.forward();
    } else {
      _animationController.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.bottomRight,
      children: [
        // 背景遮罩
        if (_isExpanded)
          Positioned.fill(
            child: GestureDetector(
              onTap: _toggleExpanded,
              child: Container(
                color: Colors.black.withValues(alpha: 0.3),
              ),
            ),
          ),

        // 快速操作按钮
        ..._buildQuickActionButtons(),

        // 主按钮
        _buildMainFAB(),
      ],
    );
  }

  /// 构建主浮动按钮
  Widget _buildMainFAB() {
    return Container(
      decoration: BoxDecoration(
        gradient: ExpenseTheme.primaryGradient,
        borderRadius: BorderRadius.circular(28.r),
        boxShadow: [
          BoxShadow(
            color: ExpenseTheme.primaryBlue.withValues(alpha: 0.3),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: FloatingActionButton(
        onPressed: _toggleExpanded,
        backgroundColor: Colors.transparent,
        elevation: 0,
        child: AnimatedBuilder(
          animation: _rotationAnimation,
          builder: (context, child) {
            return Transform.rotate(
              angle: _rotationAnimation.value * 2 * 3.14159,
              child: Icon(
                _isExpanded ? Icons.close : Icons.add,
                color: Colors.white,
                size: 28.sp,
              ),
            );
          },
        ),
      ),
    );
  }

  /// 构建快速操作按钮列表
  List<Widget> _buildQuickActionButtons() {
    if (!_isExpanded) return [];

    final actions = [
      {
        'label': '收入',
        'icon': Icons.trending_up,
        'color': ExpenseTheme.incomeGreen,
        'type': ExpenseType.income,
        'offset': const Offset(0, -80),
      },
      {
        'label': '支出',
        'icon': Icons.trending_down,
        'color': ExpenseTheme.expenseRed,
        'type': ExpenseType.expense,
        'offset': const Offset(0, -140),
      },
      {
        'label': '快速',
        'icon': Icons.flash_on,
        'color': ExpenseTheme.primaryBlue,
        'type': null,
        'offset': const Offset(-80, -80),
      },
    ];

    return actions.asMap().entries.map((entry) {
      final index = entry.key;
      final action = entry.value;
      
      return AnimatedBuilder(
        animation: _scaleAnimation,
        builder: (context, child) {
          return Transform.translate(
            offset: (action['offset'] as Offset) * _scaleAnimation.value,
            child: Transform.scale(
              scale: _scaleAnimation.value,
              child: _buildActionButton(
                action['label'] as String,
                action['icon'] as IconData,
                action['color'] as Color,
                action['type'] as ExpenseType?,
                index,
              ),
            ),
          );
        },
      );
    }).toList();
  }

  /// 构建单个操作按钮
  Widget _buildActionButton(
    String label,
    IconData icon,
    Color color,
    ExpenseType? type,
    int index,
  ) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(20.r),
            boxShadow: [
              BoxShadow(
                color: color.withValues(alpha: 0.3),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: FloatingActionButton.small(
            onPressed: () {
              _toggleExpanded();
              if (type != null) {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => AddExpenseScreen(initialType: type),
                  ),
                );
              } else {
                _showQuickAddDialog();
              }
            },
            backgroundColor: Colors.transparent,
            elevation: 0,
            child: Icon(
              icon,
              color: Colors.white,
              size: 20.sp,
            ),
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Text(
            label,
            style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w500,
              color: color,
            ),
          ),
        ),
      ],
    );
  }

  /// 显示快速添加对话框
  void _showQuickAddDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('快速记账'),
        content: const Text('选择常用的记账类型快速添加'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AddExpenseScreen(),
                ),
              );
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }
}
